import React, { Component } from 'react'

import { Modal, Form, Input, Button, Table } from 'antd';
import { connect } from 'dva';

interface IProps {
  form: any;
  loading: boolean;
  dispatch?: Function;
  children?: React.ReactNode;
  buttons?: Array<any>;
  data: {
    list: Array<any>;
    total: number;
  },
  cond?: {
    pageSize: number;
  };
  cancelMaintenance?: Function;
  visible: boolean;
}

interface CellProps {
  inputType: string;
  editing: boolean;
  dataIndex: string;
  attach: string;
  record: {};
  index: string
}

const ONE_PAGE_SIZE = 10;
const EditableContext = React.createContext({});
const addingKey = 'WAITX'

class EditableCell extends React.Component<CellProps> {

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      attach,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;

    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {
              getFieldDecorator(dataIndex, {
                initialValue: record[dataIndex],
              }
              )(<Input />)
            }
          </Form.Item>
        ) : (
            children
          )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

@connect(({ archives_devices, loading }) => ({
  data: archives_devices.cylinder || {},
  cond: archives_devices.cylinderCond || {},
}))
class ModalForm extends Component<IProps, any> {

  state = {
    current: 1,
    editingKey: '',
    data: [],
  }

  columns = [{
    title: '单个钢瓶容量(L)',
    dataIndex: 'steelCapacity',
    width: '250px',
    editable: true,
  }, {
    title: '钢瓶数量(只)',
    dataIndex: 'quantity',
    width: '250px',
    editable: true
  }, {
    title: '操作', key: 'x',
    width: '200px',
    render: (record, text, index) => {
      const { editingKey } = this.state;
      const editable = this.isEditing(record);
      return editable ? (
        <span>
          <EditableContext.Consumer>
            {form => (
              <Button type="link"
                onClick={() => this.save(form, record.key, record.id)}
              >保存</Button>
            )}
          </EditableContext.Consumer>
          <Button type="link" onClick={() => this.cancel(record.key)}
          >取消</Button>
        </span>
      ) : (
          <Button type="link"
            disabled={editingKey !== ''}
            onClick={() => this.edit(record.key)}>
            编辑</Button>
        );
    }
  }];

  handleCancel = () => {
    this.setState({ editingKey: '' },() => {
      // this.cancel(addingKey);
      this.props.cancelMaintenance()
    });
  }

  /** 可编辑cell的交互 */
  save(form, key, id) {
    const { dispatch } = this.props;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      if (key === addingKey) {
        dispatch({
          type: 'archives_devices/createCylinder',
          payload: row,
        }).then(() => {
          this.setState({ editingKey: '' }, () => this.queryData({ pageNum: 1, pageSize: ONE_PAGE_SIZE }));
        })

      } else {
        dispatch({
          type: 'archives_devices/modifyCylinder',
          payload: {
            id,
            ...row,
          },
        }).then(() => {
          this.setState({ editingKey: '' }, () => this.queryData({ pageNum: 1, pageSize: ONE_PAGE_SIZE }));

        })
      }
    });
  }

  edit(key) {
    this.setState({ editingKey: key });
  }

  cancel = (key) => {
    let { data } = this.state;
    if (key === addingKey) {
      data.splice(0, 1);
      this.setState({ editingKey: '', data });
      return;

    }
    this.setState({ editingKey: '' });
  };

  add = () => {
    const { data = [] } = this.state;
    const newData = {
      key: addingKey,
      steelCapacity: null,
      quantity: null,
    };
    this.setState({
      data: [newData, ...data],
      editingKey: addingKey
    });
  }

  queryData(params) {
    const { dispatch } = this.props;
    dispatch({
      type: 'archives_devices/queryCylinder',
      payload: params,
    }).then(() => {
      const { data } = this.props;
      this.setState({ data: data.list });
    })
  }

  isEditing = record => record.key === this.state.editingKey;

  componentDidMount() {
    this.queryData({ pageSize: ONE_PAGE_SIZE, pageNum: 1 })
  }

  initCurrent = () => {
    this.setState({
      current: 1
    })
  };

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond } = this.props;
    cond.pageSize = pageSize;
    this.setState({ current: 1 }, () => {
      dispatch({
        type: 'archives_devices/updateCylinderCond',
        payload: cond
      })
    })
  }

  render() {
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const { visible, data } = this.props;
    const { total } = data;
    const list = this.state.data;

    const ans = list && Array.isArray(list) ? list.map((item, index) => ({
      key: index,
      id: item.id,
      ...item,
    })
    ) : []
    const pagination = {
      total: total,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      current: this.state.current,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      onChange: (current) => {
        this.setState({
          current,
          isChangePage: true
        }, () => this.queryData({
          pageNum: current
        }));
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      let inputType = 'text';
      return {
        ...col,
        onCell: record => ({
          record,
          inputType,
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <Modal
        visible={visible}
        onCancel={this.handleCancel}
        maskClosable={false}
        footer={null}
        width={700}
      >
        <Button type="primary" style={{ marginTop: '30px', marginBottom: '15px', marginLeft: '590px' }} onClick={() => this.add()}>新增</Button>
        <EditableContext.Provider value={this.props.form}>
          <Table
            columns={columns}
            components={components}
            pagination={pagination}
            dataSource={ans}
            bordered
            okText="确认"
            cancelText="取消"
            loading={this.props.loading}
          />
        </EditableContext.Provider>
      </Modal>
    )
  }
}

const CylinderModal = Form.create<IProps>()(ModalForm);
export default CylinderModal;
